const util = require("../../utils/util");

const app = getApp();

Page({

  /**
   * 页面的初始数据
   */
  data: {
    // 功能区域显示
    showFunctionArea:true,
    // 自定义 tabbar
    tabbar:{},
    publisList: [
      {
        icon: '../../icons/publish/help.png',
        text: '发求助',
        subText: '缘分总会不期而遇',
        verify: 'seek'
      },
      {
        icon: '../../icons/publish/feeling.png',
        text: '发感悟',
        subText: '在平凡里照见美好',
        verify: 'topic'
      },
      {
        icon: '../../icons/publish/physical.png',
        text: '发实物',
        subText: '没有买卖，只有免费分享',
        verify: 'commodity'
      }
    ],
    tempIds: ['mIZqIcMHi1FrYDspjIvUsCt5Yhl-Vvn_oGzn_nL7IXs','LZi6-ZDijIxcvTu_eHuCJFEbMJRBkHtsFgP-kKs4kTE']
  },
  // 功能区域显示
  handleItemChange:function(params) {
    let {showFunctionArea} = params.detail;
    this.setData({
      showFunctionArea
    });

    // 获取授权信息
    if(showFunctionArea){
      this.setSubscribeMessage();
    }
  },

  // 点击关闭按钮
  closePublishHandle: function(){
    const backPage = wx.getStorageSync('backPage');

    wx.switchTab({
      url: '/' + backPage,
    })
  },

  // 验证该用户是否登录，并且填写的联系方式
  handleVerifyContact:function(options){
    let selectUrl = options.currentTarget.dataset.verify;
    let url = '';
    if(selectUrl == 'commodity'){
      url = '../pubCommodity/pubCommodity';
    } else if(selectUrl == 'seek'){
      url = '../pubSeek/pubSeek';
    } else if(selectUrl == 'topic'){
      url = '../pubTopic/pubTopic';
    }
    let userInfo = wx.getStorageSync('userInfo');
    if(userInfo == ''){
      // wx.showToast({
      //   title: '请先登录！',
      //   icon:'none',
      //   duration:2000
      // })
      wx.navigateTo({
        url: "../login/login"
      });
      return ;
    } else if(userInfo != null){
      let openid = userInfo.openid;
      let _slef = this;
      wx.request({
        url: util.BASE_URL + 'user/getHaveUserInfo',
        method: 'POST',
        header: {
          'content-type': 'application/x-www-form-urlencoded'
        }, 
        data:{
          openid
        },
        success:function(result){
          if(result.data.success == true){
            userInfo = result.data.user;
            if(userInfo.haveUserInfo == 3){
              wx.showToast({
                title: '你已经被封禁使用发布功能！',
                icon:'none',
                duration:2000
              });
              return;
            } else{
              _slef.setSubscribeMessage(url);
            }
          } else{
            wx.showToast({
              title: '用户权限获取失败！',
              icon:'none',
              duration:2000
            });
            return;
          }
        }
      })
    } 
  },


  // 判断是否开启了消息接收
  setSubscribeMessage: function(url){
    const tempIds = this.data.tempIds;
    const _slef = this;
    wx.getSetting({
      withSubscriptions: true,
      success: function(data){
        console.log('已授权信息', data);
        if(!data.subscriptionsSetting.itemSettings){
          _slef.requestmessage(url, tempIds);
        }else{
          const settings = data.subscriptionsSetting.itemSettings;
          const shouldIds = [];
          tempIds.forEach((temp, idx) => {
            if('accept' != settings[temp]){
              shouldIds.push(temp);
            }
          });
          if(shouldIds.length > 0){
            _slef.requestmessage(url, shouldIds);
          }else{
            wx.navigateTo({
              url: url
            })
          }
        }
      }
    })
  },


  requestmessage: function(url, tmplIds){
    wx.requestSubscribeMessage({
      tmplIds: tmplIds,
      success: function(res){
         console.log("订阅通知授权结果", res);
         wx.navigateTo({
           url: url
         })
      },
      fail: function(err){
         console.log("授权订阅消息失败", err);
      }
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    // 编辑自定义 tabbar
    app.editTabbar();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    // 隐藏小程序默认tabbar
    app.hidetabbar();
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    // 隐藏小程序默认tabbar
    app.hidetabbar();
    

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})